//
//  WQPictureView.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/12.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
import SDWebImage
private let pictureViewMargin: CGFloat = 5
private let pictureCellId = "pictureCellId"

class WQPictureView: UICollectionView {


    var statusViewModel: WQStatusViewModel? {
        didSet {
           //计算自己的大小，调用->sizeThatFits
            sizeToFit()
            //计算完大小重新刷新数据，不然item会重用
            reloadData()
        }
    }

    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateViewSize()
    }
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureViewMargin
        layout.minimumLineSpacing = pictureViewMargin
//        layout.itemSize = CGSizeMake(75, 75)
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        registerClass(WQPictureViewCell.classForCoder(), forCellWithReuseIdentifier: pictureCellId)
        self.backgroundColor = randomColor
        
        self.dataSource = self
        self.delegate = self
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
}

extension WQPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailUrls.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellId, forIndexPath: indexPath) as! WQPictureViewCell
        cell.pictureURL = statusViewModel?.thumbnailUrls[indexPath.item]
        return cell
    }
    
    // 点击item 发送通知
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let pramas = [WQPictureViewIndexPathKey: indexPath, WQPictureViewURLsKey: statusViewModel!.thumbnailUrls]
        
        WQNotificationCenter.postNotificationName(WQPictureViewSelectedImageNotification, object: self, userInfo: pramas)
    }
}

extension WQPictureView: WQPhotosBrowserAnimatorPresentDelegate {
    
    ///  放大缩略图到屏幕上
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        //获取沙河中存放的缩略图作为过渡图片
        let imageKey = statusViewModel?.thumbnailUrls[indexPath.item]
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageKey?.absoluteString)
        imageView.image = image
        imageView.sizeToFit()
        
        return imageView
    }
    
    //计算图片转换坐标系起始的位置
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        
        guard let cell = self.cellForItemAtIndexPath(indexPath) else {
            return CGRectZero
        }
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
    }
    ///计算图片到最终位置
    func photoBrowserPresetnToRect(indexPath: NSIndexPath) -> CGRect {
        //获取沙河中存放的缩略图
        let imageKey = statusViewModel?.thumbnailUrls[indexPath.item]
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageKey?.absoluteString) else {
            return CGRectZero
        }
        //按图片比例计算出放大后的最终尺寸
        let width = UIScreen.mainScreen().bounds.width
        let height = image.size.width * width / image.size.height
        //计算放大图片的最终位置x,y
        var imageEndY: CGFloat = 0
        let screenHeight = UIScreen.mainScreen().bounds.height
        if height < screenHeight {
            imageEndY = (screenHeight - height) * 0.5
        }
        return CGRectMake(0, imageEndY, width, height)
    }
}


extension WQPictureView {
    private func calculateViewSize() -> CGSize {
        
        let columsCount = 3
        let maxWith = UIScreen.mainScreen().bounds.width - CGFloat(homeCellSubViewsMargin) * 2
        let itemW = (maxWith - pictureViewMargin * 2) / CGFloat(columsCount)
        let layout =  collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemW, itemW)
        
        let pictureCount = statusViewModel?.thumbnailUrls.count ?? 0
        // 1> 没有图片
        if pictureCount == 0 {
            layout.itemSize = CGSizeMake(0.5, 0.5)
            return CGSizeMake(1, 1)
        }
        // 2> 一张图片
        
        
            
        var size = CGSizeMake(90, 120)
        if pictureCount == 1{
                dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
                
                //SDWebImage的缓存Key为URL的全路径对MD5值
                
                if let url = self.statusViewModel?.thumbnailUrls.first {
                    
                    if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString){
                    size = image.size
                    }
                }
            }
                if size.width < 60 {
                    size.width = 60
                    
                }
                if size.width > 300 {
                    let width: CGFloat = 300
                    size.height = size.height * width / size.width
                }
                
                
                    layout.itemSize = size
                
                    return size
        }
        
        // 3> 四张图片 2 * 2 的大小
        if pictureCount == 4 {
            
            let pictureWH = (itemW + pictureViewMargin) * 2 - pictureViewMargin
            
            return CGSizeMake(pictureWH + 1, pictureWH + 1)
        }
        // 4> 其他图片 按照九宫格来显示
        let rowCount =  CGFloat((pictureCount - 1) / Int(columsCount) + 1)
        
        let pictureW = (itemW + pictureViewMargin) * 3 - pictureViewMargin
        
        let pictureH = (itemW + pictureViewMargin) * rowCount - pictureViewMargin
        
        return CGSizeMake(pictureW + 1, pictureH + 1)
    }
}


